package com.question.common.valid;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.question.business.dict.model.dto.DictCacheDTO;
import com.question.business.dict.repository.IDictCacheRepository;
import com.question.common.annotation.DictValid;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 枚举校验处理类
 *
 * @author star
 * @since 2021-12-29
 */
@Slf4j
@Component
public class DictValidator implements ConstraintValidator<DictValid, Object> {

    @Resource
    private IDictCacheRepository dictCacheRepository;

    private DictValid annotation;

    @Override
    public void initialize(DictValid constraintAnnotation) {
        annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        try {
            String type = annotation.type();
            // 忽视空值，不校验
            if (value instanceof List) {
                List list = (List) value;
                if (CollectionUtils.isEmpty(list)) {
                    return true;
                } else {
                    for (Object obj : list) {
                        boolean isEquals = dataEquals(obj, type);
                        if (!isEquals) {
                            return false;
                        }
                    }
                }
            } else {
                if (value instanceof String) {
                    String validData = (String) value;
                    if (StringUtils.isNotBlank(validData)) {
                        return dataEquals(value, type);
                    }
                } else {
                    if (Objects.nonNull(value)) {
                        return dataEquals(value, type);
                    }
                }
            }
        } catch (Exception e) {
            log.error("DictValidator 校验异常", e);
        }
        return true;
    }

    /**
     * 比对数据
     *
     * @param value 数据值
     * @param type  字典类型
     * @return boolean
     */
    private boolean dataEquals(Object value, @NotNull String type) {
        Map<String, DictCacheDTO> map = dictCacheRepository.queryMapByType(type);
        for (Map.Entry<String, DictCacheDTO> entry : map.entrySet()) {
            DictCacheDTO dto = entry.getValue();
            // 获取code
            String code = dto.getDictCode();
            // 对比值
            if (Objects.deepEquals(String.valueOf(value), code)) {
                return true;
            }
        }
        return false;
    }
}
